package org.spring.springboot.app.sys.systemoption.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spring.springboot.app.base.Constants;
import org.spring.springboot.app.sys.systemoption.dao.SystemOptionDao;
import org.spring.springboot.app.sys.systemoption.domain.po.SystemOptionPO;
import org.spring.springboot.app.sys.systemoption.service.ISystemOptionService;
import org.spring.springboot.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class SystemOptionServiceImpl implements ISystemOptionService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SystemOptionServiceImpl.class);

    @Autowired
    private SystemOptionDao systemOptionDao;

    // key生成器,redis生成key必须用
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void init() {
        List<SystemOptionPO> list = systemOptionDao.findAll();
        redisUtils.set(Constants.SYSTEMOPTION_REDIS_KEY, list, 60 * 60 * 24 * 365, TimeUnit.SECONDS);
    }

    public String getString(String key) {
        String value = getOption(key);
        if (value != null) {
            return value;
        }
        return null;
    }
    public Integer getInt(String key){
        String value = getOption(key);
        if (value != null) {
            return Integer.parseInt(value);
        }
        return null;
    }
    public Long getLong(String key){
        String value = getOption(key);
        if (value != null) {
            return Long.parseLong(value);
        }
        return null;
    }
    public Double getDouble(String key){
        String value = getOption(key);
        if (value != null) {
            return Double.parseDouble(value);
        }
        return null;
    }
    public Boolean getBoolean(String key){
        String value = getOption(key);
        if (value != null) {
            return Boolean.getBoolean(value);
        }
        return null;
    }

    private String getOption(String key) {
        List<SystemOptionPO> list = redisUtils.get(Constants.SYSTEMOPTION_REDIS_KEY);
        if (list != null) {
            for (SystemOptionPO po : list) {
                if(key.trim().equals(po.getSokey())){
                    return po.getSovalue();
                }
            }
        }
        return null;
    }


}
